import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeleteResult, Repository, UpdateResult } from 'typeorm';
import * as fs from 'fs';
import { join } from 'path';
import { v1 } from 'node-uuid';
import { Bk_News } from './bk_news.entity';

@Injectable()
export class NewsService {
    constructor(
        @InjectRepository(Bk_News)
        private readonly newsRepository: Repository<Bk_News>
    ) { }

    async upload(files: any, body: any): Promise<any> {
        const image = v1() + '.' + files.image[0].originalname.split('.')[1];
        fs.writeFileSync(join(__dirname, '..', 'public', 'image', image), files.image[0].buffer);
        return {
            errno: 0, // 注意：值是数字，不能是字符串
            data: {
                url: `http://127.0.0.1:3000/image/${image}` // 图片 src ，必须
                // alt: "yyy", // 图片描述文字，非必须
                // href: "zzz" // 图片的链接，非必须
            }
        };
    }

    async add(files: any, news: any): Promise<Bk_News> {
        news.thumbnail_path = v1() + '.' + files.thumbnail[0].originalname.split('.')[1];
        fs.writeFileSync(join(__dirname, '..', 'public', 'image', news.thumbnail_path), files.thumbnail[0].buffer);
        return await this.newsRepository.save(news);
    }

    async delete(id: number): Promise<DeleteResult> {
        return await this.newsRepository.delete(id);
    }

    async update(id: number, news: any, files): Promise<UpdateResult> {
        if (files.thumbnail?.length > 0) {
            fs.unlinkSync(join(__dirname, '..', 'public', 'image', news.thumbnail_path));
            news.thumbnail_path = v1() + '.' + files.thumbnail[0].originalname.split('.')[1];
            fs.writeFileSync(join(__dirname, '..', 'public', 'image', news.thumbnail_path), files.thumbnail[0].buffer);
        }
        return await this.newsRepository.update(id, news);
    }

    async findAll(query: any): Promise<[Bk_News[], number]> {
        return await this.newsRepository.findAndCount({
            relations: ["category"],
            skip: query.skip,
            take: query.take,
            order: { order_number: "ASC" }
        });
    }

    async getNewsByCategory(query: any): Promise<[Bk_News[], number]> {
        return await this.newsRepository.findAndCount({
            relations: ["category"],
            where: { category: { id: query.id } },
            skip: query.skip,
            take: query.take,
            order: { order_number: "ASC" }
        });
    }

    async getNewsById(query: any): Promise<Bk_News> {
        return await this.newsRepository.findOne({ relations: ["category"], where: { id: query.id } });
    }
}